# -*- coding: UTF-8 -*-
"""
@Project ：swift-forge-engine 
@File    ：login_log_service
@IDE     ：PyCharm 
@Author  ：Tony
@Date    ：2025/2/21 9:17 
@Des     ：
"""
from datetime import datetime

from fastapi import Request
from sqlalchemy import Select
from sqlalchemy.ext.asyncio import AsyncSession

from App.app.admin.crud.login_log_crud import LoginLogDao
from App.app.admin.schemas.login_log_schema import CreateLoginLogParam
from App.common.security.jwt import superuser_verify
from App.config.log_conf import log
from App.database.mysql import async_db_session


class LoginLogServices:
    @staticmethod
    async def get_select(*, username: str, status: str, ip: str, sort_field: str = None,
                         sort_order: str = None) -> Select:
        return await LoginLogDao.get_list(username=username, status=status, ip=ip, sort_field=sort_field,
                                          sort_order=sort_order)

    @staticmethod
    async def create(
            *,
            db: AsyncSession,
            request: Request,
            user_id: int,
            username: str,
            login_time: datetime,
            status: int,
            message: str,
    ) -> None:
        try:
            obj_in = CreateLoginLogParam(
                user_id=user_id,
                username=username,
                status=status,
                ip=request.state.ip,
                country=request.state.country,
                region=request.state.region,
                city=request.state.city,
                user_agent=request.state.user_agent,
                browser=request.state.browser,
                os=request.state.os,
                device=request.state.device,
                message=message,
                login_time=login_time,
            )
            await LoginLogDao.create(db, obj_in)
        except Exception as e:
            log.error(f'登录日志创建失败: {e}')

    @staticmethod
    async def delete(*, request: Request, pk: list[int]) -> int:
        async with async_db_session.begin() as db:
            superuser_verify(request)
            count = await LoginLogDao.delete(db, pk)
            return count

    @staticmethod
    async def delete_all(request: Request) -> int:
        async with async_db_session.begin() as db:
            superuser_verify(request)
            count = await LoginLogDao.delete_all(db)
            return count


LoginLogService: LoginLogServices = LoginLogServices()
